{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "# Only works on Unix/Linux/Mac:\n",
    "# res = os.fork()\n",
    "# if res == 0: \n",
    "#     print('这是子进程%s' % os.getpid())\n",
    "# else:\n",
    "#     print('这是父进程%s' % os.getppid())\n",
    "# https://c.runoob.com/compile/9"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "parent process 46584\n"
     ]
    }
   ],
   "source": [
    "# %%writefile 1.py\n",
    "\n",
    "from multiprocessing import Process\n",
    "def test(i):\n",
    "    print('----1111----%s----%s' % (os.getpid(),os.getppid()),i)\n",
    "    \n",
    "if __name__=='__main__':\n",
    "    print('parent process %s' % os.getpid())\n",
    "    for i in range(10):\n",
    "        p = Process(target=test,args=(i,)) #,name='test'+str(i)\n",
    "        p.start()\n",
    "        p.join()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ! 1.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing 2.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile 2.py\n",
    "\n",
    "from multiprocessing import Pool\n",
    "import os,time,random\n",
    "\n",
    "def worker(msg):\n",
    "    t_start = time.time()\n",
    "    print('%s开始执行，进程号为%d' % (msg,os.getpid()))\n",
    "    time.sleep(random.random())\n",
    "    t_stop = time.time()\n",
    "    print(msg,'执行完毕，耗时%0.2f' % (t_stop-t_start))\n",
    "\n",
    "def main():\n",
    "    po = Pool(3)\n",
    "    for i in range(10):\n",
    "        po.apply_async(worker,(i,))\n",
    "    \n",
    "    print('----start----')\n",
    "    po.close()\n",
    "    po.join()\n",
    "    print('----end----')\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
